package com.study.crud.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.study.crud.model.emp.Emp;
import com.study.crud.model.job.Job;
import com.study.crud.service.EmpService;
import com.study.crud.service.JobService;
import com.study.crud.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/job")
public class JobController {

    @Resource
    private JobService jobService;

    @Resource
    private EmpService empService;

    @Resource
    private UserService userService;

    @RequestMapping("/findAll")
    public String findAll(Model model){
        List<Job> jobList = jobService.list(new QueryWrapper<>());
        model.addAttribute("jobList",jobList);
        List<Emp> empList = empService.list(new QueryWrapper<>());
        model.addAttribute("empList",empList);
        return "job/jobList";
    }

    @RequestMapping("/toAdd")
    public String toAdd(Model model){
        List<Emp> empList = empService.list(new QueryWrapper<>());
        model.addAttribute("empList",empList);
        return "job/addJob";
    }

    @RequestMapping("/add")
    public String add(Job job){
        jobService.save(job);
        return "redirect:/job/findAll";
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(Integer jid,Model model){
        List<Emp> empList = empService.list(new QueryWrapper<>());
        model.addAttribute("empList",empList);
        Job job = jobService.getById(jid);
        model.addAttribute("job",job);
        return "job/updateJob";
    }

    @RequestMapping("/update")
    public String update(Job job){
        jobService.updateById(job);
        return "redirect:/job/findAll";
    }

    @RequestMapping("/deleteByJid")
    public String deleteByJid(Integer jid){
        Integer num = userService.findNumByJid(jid);
        if (num==0){
            jobService.removeById(jid);
            return "redirect:/job/findAll";
        }
        return "error/error_deleteJob";
    }
}
